/*
 * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package sun.misc;

import java.lang.ref.*;
import java.security.AccessController;
import java.security.PrivilegedAction;


/**
 * General-purpose phantom-reference-based cleaners.
 *
 * <p> Cleaners are a lightweight and more robust alternative to finalization.
 * They are lightweight because they are not created by the VM and thus do not
 * require a JNI upcall to be created, and because their cleanup code is
 * invoked directly by the reference-handler thread rather than by the
 * finalizer thread.  They are more robust because they use phantom references,
 * the weakest type of reference object, thereby avoiding the nasty ordering
 * problems inherent to finalization.
 *
 * <p> A cleaner tracks a referent object and encapsulates a thunk of arbitrary
 * cleanup code.  Some time after the GC detects that a cleaner's referent has
 * become phantom-reachable, the reference-handler thread will run the cleaner.
 * Cleaners may also be invoked directly; they are thread safe and ensure that
 * they run their thunks at most once.
 *
 * <p> Cleaners are not a replacement for finalization.  They should be used
 * only when the cleanup code is extremely simple and straightforward.
 * Nontrivial cleaners are inadvisable since they risk blocking the
 * reference-handler thread and delaying further cleanup and finalization.
 *
 *
 * @author Mark Reinhold
 *
 * <pre>
 * 1. Cleaner的核心机制
 *
 *  Cleaner 是java中的 资源自动清理机制：通过 "虚引用" 和 "引用队列" 实现资源释放。
 *  Cleaner 继承自 PhantomReference，所以 Cleaner本质上就是一个虚引用。
 *
 * 1.1 Cleaner的工作流程
 *   1). 注册Cleaner：在创建 Cleaner（虚引用） 对象时，它会关联 目标对象（referent）和 一个引用队列（dummyQueue）。
 *   2). 当目标对象变为不可达时，也就是没有强引用指向它时，GC 会把 Cleaner（虚引用）加入到 dummyQueue（引用队列） 中。
 *   3). 后台线程处理：Reference Handler 线程（JVM内置的高优先级守护线程）会不断轮询 引用队列，取出所有 Cleaner 对象并调用 clean() 方法执行清理任务。
 *
 * 2. 直接内存清理机制
 * 2.1 DirectByteBuffer的内存分配流程
 *   1). 分配内存：通过 ByteBuffer.allocateDirect() 方法分配内存，本质上是通过 Unsafe.allocateMemory() 方法分配内存。
 *   2). 注册Cleaner：在创建 DirectByteBuffer 对象时，会创建一个 Cleaner 对象，
 *       Cleaner对象会 关联 目标对象（DirectByteBuffer）和 清理任务（Dellocator）。
 *   3). 清理逻辑：当 DirectByteBuffer 被回收时，Cleaner 的 Dellocator 会调用 Unsafe.freeMemory() 方法释放内存。
 *
 * 3. 直接内存的清理动作由GC完成的原理
 * GC触发的时机：当 DirectByteBuffer对象（目标对象）变为 不可达时（比如，被设置为 null 且 没有其他引用），GC会将其标记为 可回收。
 * Cleaner的自动清理：
 *   1). GC 将 Cleaner（虚引用） 加入到 引用队列（ReferenceQueue）中。
 *   2). Reference Handler 线程 从 引用队列中取出 Cleaner，并调用 Cleaner 的 clean() 方法执行清理任务。
 *   3). Cleaner 的 Dellocator.run() 会调用 Unsafe.freeMemory() 方法释放内存。
 * </pre>
 */

public class Cleaner
    extends PhantomReference<Object>
{

    // Dummy reference queue, needed because the PhantomReference constructor
    // insists that we pass a queue.  Nothing will ever be placed on this queue
    // since the reference handler invokes cleaners explicitly.
    //
    private static final ReferenceQueue<Object> dummyQueue = new ReferenceQueue<>();

    // Doubly-linked list of live cleaners, which prevents the cleaners
    // themselves from being GC'd before their referents
    //
    static private Cleaner first = null;

    private Cleaner
        next = null,
        prev = null;

    private static synchronized Cleaner add(Cleaner cl) {
        if (first != null) {
            // 尾插法
            cl.next = first;
            first.prev = cl;
        }
        first = cl;
        return cl;
    }

    private static synchronized boolean remove(Cleaner cl) {

        // If already removed, do nothing
        if (cl.next == cl)
            return false;

        // Update list
        if (first == cl) {
            if (cl.next != null)
                first = cl.next;
            else
                first = cl.prev;
        }
        if (cl.next != null)
            cl.next.prev = cl.prev;
        if (cl.prev != null)
            cl.prev.next = cl.next;

        // Indicate removal by pointing the cleaner to itself
        cl.next = cl;
        cl.prev = cl;
        return true;

    }

    private final Runnable thunk;

    private Cleaner(Object referent, Runnable thunk) {
        // 关联 目标对象（referent） 和 引用队列（dummyQueue）
        super(referent, dummyQueue);
        this.thunk = thunk;
    }

    /**
     * Creates a new cleaner.
     *
     * @param  ob the referent object to be cleaned 目标对象
     * @param  thunk 清理任务
     *         The cleanup code to be run when the cleaner is invoked.  The
     *         cleanup code is run directly from the reference-handler thread,
     *         so it should be as simple and straightforward as possible.
     *
     * @return  The new cleaner
     */
    public static Cleaner create(Object ob, Runnable thunk) {
        if (thunk == null)
            return null;
        return add(new Cleaner(ob, thunk));
    }

    /**
     * Runs this cleaner, if it has not been run before.
     * 显式释放 直接缓冲区 占用的内存。
     */
    public void clean() {
        if (!remove(this))
            return;
        try {
            thunk.run();
        } catch (final Throwable x) {
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        if (System.err != null)
                            new Error("Cleaner terminated abnormally", x)
                                .printStackTrace();
                        System.exit(1);
                        return null;
                    }});
        }
    }

}
